package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Provider;

@Repository(value = "providerDao")
@Transactional(readOnly = false)
public class ProviderDaoImpl implements ProviderDao{
	private EntityManager em = null;
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	public List<Provider> getlistProviders() {
		TypedQuery<Provider> providers = em.createNamedQuery("Provider.findByActive", Provider.class);
		providers.setParameter("active",true);
    	return providers.getResultList();
	}
	
	public List<Provider> getlistProvidersDischarged() {
		TypedQuery<Provider> providers = em.createNamedQuery("Provider.findByActive",Provider.class);
		providers.setParameter("active",false);
    	return providers.getResultList();
	}
	
	
	public List<Provider> getListProvider(boolean active) {
		TypedQuery<Provider> providers = em.createNamedQuery("Provider.findByActive", Provider.class);
		providers.setParameter("active",active);
    	return providers.getResultList();
	}
	
	public void add(Provider provider) {
		em.persist(provider);
	}
	public void update(Provider provider) {
		em.merge(provider);
	}
	public void remove(Provider provider) {
		em.remove(em.getReference(Provider.class,provider.getProviderId()));
	}
	public Provider findProviderByProviderId(Integer providerId) {
		Provider res=null;
		try {
			res=em.find(Provider.class,providerId);
		} catch (Exception e) {
			// TODO: handle exception
		}
    	return res;
	}
	public Integer findByProviderIdMax(){
		Integer res=0;
		if(!this.getlistProviders().isEmpty()){
			try {
				res=(Integer)em.createNamedQuery("Provider.findByProviderIdMax").getSingleResult();
			} catch (Exception e) {}
		}
		return res;
	}
}
